package top.lishuoboy.dependency.base.net;

import cn.hutool.core.net.NetUtil;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * 网络工具
 *
 * @author lishuoboy
 */
@Slf4j
public class MyNetUtil {
    /** localhost */
    public static final String LOCALHOST = "localhost";
    /** 本地 IPv4 */
    public static final String LOCAL_IP_V4 = "127.0.0.1";
    /** 本地 IPv6,缩写 */
    public static final String LOCAL_IP_V6 = "::1";
    /** 本地 IPv6,全称 */
    public static final String LOCAL_IP_V6_FULL = "0:0:0:0:0:0:0:1";

    /** 获取内网IPv4们 */
    public static List<String> getIntranetIpv4s() {
        List<String> ipv4List = new LinkedList<>();
        Set<String> ipv4s = NetUtil.localIpv4s();
        for (String ipv4 : ipv4s) {
            if (!ipv4.contains("127.0.0.1")) {
                ipv4List.add(ipv4);
            }
        }
        return ipv4List;
    }

    /** 获取内网IPv6们 */
    public static List<String> getIntranetIpv6s() {
        List<String> ipv6List = new LinkedList<>();
        Set<String> ipv6s = NetUtil.localIpv6s();
        for (String ipv6 : ipv6s) {
            if (!ipv6.contains("0:0:0:0:0:0:0:1") && !ipv6.contains("::1") && !ipv6.contains("%")) {
                ipv6List.add(ipv6);
            }
        }
        return ipv6List;
    }

    /** 获取公网IPv4 */
    public static String getInternetIpV4(int timeout) {
        try {
            String ipv4 = HttpUtil.get("4.ipw.cn", timeout);
            log.info("获取公网IPv4成功,IPv4==【{}】", ipv4);
            return ipv4;
        } catch (Exception e) {
            log.warn("获取公网IPv4异常", e);
            return "";
        }
    }

    /** 获取公网IPv6 */
    public static String getInternetIpV6(int timeout) {
        try {
            return HttpUtil.get("6.ipw.cn", timeout);
        } catch (Exception e) {
            log.info("获取公网IPv6异常", e);
            return "";
        }
    }

    /** 获取主机名 */
    public static String getHostname() {
        try {
            String hostname = InetAddress.getLocalHost().getHostName();
            log.info("hostname=={}", hostname);
            return hostname;
        } catch (UnknownHostException e) {
            log.info("获取主机名异常", e);
            return "";
        }
    }
}